from flask import Flask, request, redirect, url_for,abort,jsonify
from flask_cors import CORS
import os
import dbApi
import utils
import config
from jinja2 import Environment, FileSystemLoader


from PIL import Image



app = Flask(__name__)

CORS(app,  resources={r"/*": {"origins": "*"}})

@app.route("/getHtmlInformation",methods=['get'])
def getHtmlInformation():
    ret = dbApi.getHtmlInformation()
    return jsonify(dict(ec=0,data=ret))

@app.route('/upload', methods=['POST'])
def upload():
    try:
        image = request.files['file']
        version = request.form.get('version')
        webPageFileName = request.form.get('webPageFileName') + '_'+version
        title = request.form.get('title')
        # 暂时注释掉验证码验证和utils导入
        htmlImageSrc = os.path.join(config.IMAGE_FOLDER, webPageFileName  + '.png')
        imagePath = os.path.join(config.PROJECT_PATH,config.HTML_FOLDER+htmlImageSrc)
        image.save(imagePath)
        with Image.open(imagePath) as img:
            dominantColor = img.quantize(colors=1).getpalette()[:3]
        backgroundColor = "#{:02x}{:02x}{:02x}".format(*dominantColor)
        # 创建一个Jinja2环境
        env = Environment(loader=FileSystemLoader('.'))
        # 加载模板
        template = env.get_template('template.html')
        # 渲染模板
        html = template.render(title=title, backgroundColor=backgroundColor, htmlImageSrc=htmlImageSrc )

        htmlPath = os.path.join(config.PROJECT_PATH,config.HTML_FOLDER, webPageFileName + '.html')
        with open(htmlPath, 'w',encoding='utf-8') as f:
            f.write(html)

        utils.git_operation(title)


        ret = dbApi.addHtmlInformation(webPageFileName,title)

        data = {
            'message': f"HTML 文件 [{title}] 已经生成并推送到 Git.",
            'data':ret
        }
        return jsonify(dict(ec=200,data=data))
    except Exception as e:
        # 错误处理
        errorMessage = f"Error: {str(e)}"
        # 返回错误信息给客户端
        return jsonify(dict(ec=500,data={'message':errorMessage}))

if __name__ == '__main__':
  print("Starting application...")
  print("Initializing database...")
  dbApi.saveHtmlInformation()
  print("Database initialized, starting Flask server...")
  app.run(port=5000, host='0.0.0.0', debug=True)

